<script setup>
import { useSystermStore } from '@/stores';
import { buttonClicked } from '@/utils/tool';
import { getUserInfo } from '@/api/profile';
import { isUnoccupiedPowerBank, getSiteList, hasRentOrder } from '@/api/my';
// import AdverTisement from '@/components/Advertisement.vue';
const scanResult = ref('');
const end = ref('');
const buttonClickedState = ref(false);
const orderNotice = ref(false);
const bottomHeight = ref(900); // 默认广告组件底部高度

//获取屏幕边界到安全区域距离
const systerm = useSystermStore();
console.log(systerm.safeArea);
const top = systerm.safeArea.top + 'px';

//按钮数据
const buttons = [
  { id: 1, icon: '/static/images/home_my.png', text: '个人中心', link: '/pages/my/my' },
  { id: 2, icon: '/static/images/home_order.png', text: '我的订单', link: '/pages/order/order' },
  { id: 3, icon: '/static/images/home_customer.png', text: '在线客服', link: '/pages/customer/customer' },
  { id: 4, icon: '/static/images/home_store.png', text: '附近门店', link: '/pages/store/store' }
];

const navigate = (link) => {
  uni.navigateTo({
    url: link,
    fail: (err) => {
      console.error(`导航失败：${err.errMsg}`);
    }
  });
};

// 扫码
const handleScan = async () => {
  buttonClicked(buttonClickedState);
  try {
    await handleScanResult();
    await getUserInfo();
    const boxCheck = await isUnoccupiedPowerBank(scanResult.value);
    console.log(boxCheck);
    if (boxCheck) {
      const qrcode = encodeURIComponent(end.value.result);
      console.log(qrcode);
      uni.redirectTo({
        url: `/pages/rentRule/rentRule?q=${qrcode}`
      });
    }
  } catch (error) {
    console.error('Error during scan:', error);
  }
};

// 扫码结果处理
const handleScanResult = () => {
  return new Promise((resolve, reject) => {
    uni.scanCode({
      onlyFromCamera: true,
      success(res) {
        if (!res || !res.result || res.result.indexOf('?id=') == -1) {
          uni.showToast({
            title: '非正确二维码',
            icon: 'warn',
            duration: 1500
          });
          return;
        }
        const serverUrl = 'https://s.chengdiankeji.com.cn/sw/';
        console.log('----->', serverUrl);

        console.log('----->', res.result);
        if (!res.result.includes(serverUrl)) {
          // 请替换 serverUrl 为实际值
          uni.showModal({
            title: '提示',
            content: '未识别该品牌柜机二维码',
            showCancel: false
          });
          return;
        }
        end.value = res;
        scanResult.value = res.result.split('=')[1];
        resolve(true);
      },
      fail(err) {
        console.error('扫码失败', err);
        reject(err);
      }
    });
  });
};

// 最近网点数据
const nearestSite = ref(null);
const showNoSiteMessage = ref(false);

// 获取最近的网点
const fetchNearestSite = async (longitude, latitude) => {
  try {
    const map = TXMapToBMap(longitude, latitude);
    console.log('map', map);
    const distance = 5; // 默认值为5公里
    const total = 1; // 获取最近的一个网点
    const queryParam = {
      lng: map[0],
      lat: map[1],
      distance: Number(distance),
      total: Number(total)
    };
    const res = await getSiteList(queryParam);
    if (res && res.data && res.data.length > 0) {
      nearestSite.value = res.data[0];
    } else {
      showNoSiteMessage.value = true;
    }
  } catch (error) {
    showNoSiteMessage.value = true;
    console.error('fetchNearestSite error:', error);
  }
};

// 获取用户位置
const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        uni.showModal({
          title: '提示',
          content: '未能获取当前位置,请在设置中授权位置信息',
          showCancel: false
        });
        reject(err);
      }
    });
  });
};

// 腾讯地图转百度地图
const TXMapToBMap = (lng, lat) => {
  if (!lng || !lat) return [lng, lat];
  const x_pi = 3.14159265358979324;
  const x = parseFloat(lng);
  const y = parseFloat(lat);
  const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  const newLng = (z * Math.cos(theta) + 0.0065).toFixed(5);
  const newLat = (z * Math.sin(theta) + 0.006).toFixed(5);
  return [Number(newLng), Number(newLat)];
};

// 百度坐标转腾讯坐标
const go = (lng, lat, name) => {
  const x_pi = (3.14159265358979324 * 3000.0) / 180.0;
  const x = lng - 0.0065;
  const y = lat - 0.006;
  const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  const gcjLon = z * Math.cos(theta);
  const gcjLat = z * Math.sin(theta);
  uni.openLocation({
    latitude: gcjLat,
    longitude: gcjLon,
    name: name
  });
};

// 查询已经登陆过的用户的租借中的订单
const handleOrderNotice = async () => {
  try {
    const res = await hasRentOrder();
    if (res.data) {
      orderNotice.value = true;
      // 添加跳转逻辑
      buttonClicked(buttonClickedState);
      uni.navigateTo({
        url: '/pages/order/order',
        fail: (err) => {
          console.error(`导航失败：${err.errMsg}`);
        }
      });
    }
  } catch (error) {
    console.error('查询租借中的订单失败:', error);
  }
};

/**
 * 生命周期函数--监听页面加载
 */
onLoad(async () => {
  try {
    const location = await getUserLocation();
    await fetchNearestSite(location.longitude, location.latitude);
  } catch (error) {
    console.error('获取用户位置失败:', error);
  }
});
handleOrderNotice();
</script>

<template>
  <view class="container" :style="{ paddingTop: top }">
    <view class="container_title">
      <view class="text_1">大容量充电宝</view>
      <view class="text_1">比你想象的更快一些</view>
    </view>
    <!-- ad-intervals 表示广告组件自动刷新广告内容的时间间隔，以秒为单位 -->
    <!-- #ifdef MP-WEIXIN  -->
    <!-- <AdverTisement :bottomHeight="bottomHeight" /> -->
    <!-- #endif -->
    <view style="position: fixed; top: 154rpx; width: 750rpx; z-index: 100">
      <cover-view @click="handleOrderNotice" class="orderNotice_1" v-if="orderNotice">
        <cover-image src="@/static/images/mini_battery.gif" style="width: 62rpx; height: 30rpx; margin-left: 60rpx"></cover-image>
        <cover-view style="margin-left: 20rpx" class="order">你有一笔订单正在进行中...</cover-view>
      </cover-view>
    </view>
    <view class="images">
      <img src="@/static/images/icon_bg.png" />
    </view>
    <view class="footer">
      <view class="footer_buttons">
        <button v-for="item in buttons" :key="item.id" class="footer_button" @click="navigate(item.link)" type="default" size="default">
          <image :src="item.icon" class="footer_icon" />
          <view class="footer_text">
            {{ item.text }}
          </view>
        </button>
      </view>
      <uni-card v-if="nearestSite" @click="go(nearestSite.lng, nearestSite.lat, nearestSite.name)" class="footer_card" :thumbnail="avatar">
        <!-- <img src="@/static/images/icon_copo.png" alt="" class="text_img" /> -->
        <view class="text_container">
          <view class="text_name">
            <text class="lately">最近</text>
            <text class="title">{{ nearestSite.name }}</text>
          </view>
          <view class="title_2">{{ nearestSite.address }}</view>
          <view class="title_2">营业时间: {{ nearestSite.open_time }}</view>
        </view>
        <view class="text_status">
          <view class="status_container">
            <text :style="{ color: nearestSite.borrow ? '#10C0B9' : '#616169' }" class="status">{{ nearestSite.borrow ? '可租借' : '不可租借' }}</text>
            <text :style="{ color: nearestSite.empty ? '#10C0B9' : '#616169' }" class="status">{{ nearestSite.empty ? '可归还' : '不可还' }}</text>
          </view>
          <view class="text_distance">
            <text>距离{{ nearestSite.distanceCn }}</text>
          </view>
        </view>
      </uni-card>
      <view v-else-if="showNoSiteMessage" style="text-align: center">暂无网点信息</view>
      <view class="footer_sweep">
        <button type="default" class="footer_text1" @click="handleScan">
          <image src="@/static/images/icon_sweep.png" class="icon_saoyisao" />
          租借充电宝
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
$primary-color: #ff6700;
$secondary-color: #889dba;
$background-color: #e8f1f8;
$font-color: #333;
$light-color: #ececec;

@mixin flex-center {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

@mixin text-style($size, $weight: normal, $color: $font-color) {
  font-size: $size;
  font-weight: $weight;
  color: $color;
}

page {
  display: flex;
  height: 100%;
  flex-direction: column;
}

.uni-card {
  margin: 0rpx 20rpx !important;
  border-radius: 20rpx !important;
}

.container {
  padding-top: 57px !important;
  background: linear-gradient(to bottom, $background-color 0%, $secondary-color 100%);
  .orderNotice_1 {
    display: flex;
    align-items: center;
    top: 0;
    width: 100%;
    height: 74rpx;
    background: rgba(232, 255, 254, 1);
    .order {
      font-size: 26rpx;
      font-weight: 400;
      color: rgba(0, 189, 181, 1);
    }
  }

  .container_title {
    text-align: center;

    .text_1 {
      margin-top: 10rpx;
      @include text-style(45rpx, bold);
    }
  }

  .images {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    padding-top: 20rpx;
    height: 46vh;
  }
  .uni-card__content {
    padding: 0 !important;
  }
  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 40vh;
    box-sizing: border-box;
    background-color: #ececec;
    border-radius: 50rpx 50rpx 0 0;

    .footer_buttons {
      display: flex;
      justify-content: space-around;
      background-color: #ffffff;
      border-radius: 50rpx 50rpx 0 0;

      button::after {
        border: none;
      }

      .footer_button {
        padding-top: 10rpx;
        background-color: #ffffff;
        border-radius: 100rpx 100rpx 0 0;

        .footer_icon {
          width: 45rpx;
          height: 48rpx;
        }

        .footer_text {
          @include text-style(28rpx, bold);
          margin-top: -30rpx;
        }
      }
    }

    .footer_card {
      padding: 10rpx;
      .text_container {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        width: 450rpx;
        margin-top: 20rpx;

        .lately {
          padding: 8rpx;
          margin-right: 10rpx;
          border: 2rpx solid $primary-color;
          border-radius: 8rpx;
          @include text-style(22rpx, normal, $primary-color);
          vertical-align: top;
        }

        .title {
          display: inline-block;
          @include text-style(30rpx, bold);
        }

        .title_2 {
          margin-top: 15rpx;
          @include text-style(24rpx);
        }
      }

      .text_status {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30rpx;

        .status_container {
          flex: 1;
          margin-top: 20rpx;
          width: 80rpx;

          .status {
            padding: 16rpx;
            @include text-style(24rpx, normal, $secondary-color);
            background-color: $light-color;
            box-sizing: border-box;

            &:hover {
              color: $primary-color;
            }
          }
        }

        .text_distance {
          margin-top: 20rpx;
          @include text-style(26rpx, bold);
        }
      }
    }

    .footer_sweep {
      @include flex-center;
      margin-bottom: 40rpx;

      .footer_text1 {
        width: 600rpx;
        height: 100rpx;
        border-radius: 100rpx;
        line-height: 100rpx;
        font-size: 32rpx;
        color: #ffffff;
        white-space: nowrap;
        background-color: $primary-color;
        .icon_saoyisao {
          width: 50rpx;
          height: 50rpx;
          line-height: 50rpx;
          vertical-align: middle;
          margin-right: 10rpx;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
